package com.zhenyi.xiaohuoche.admin.web;

import java.util.List;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.xhc.common.model.XhcAdv;

public class AdvController extends XHCAdminController {

	@Override
	public void list() {
		Integer type = getParaToInt("type", 1);
		if (type == null) {
			renderError(404);
			return;
		}
		SqlPara sqlPara = xhcDb.getSqlPara("XHCAdvList", type);
		Page<XhcAdv> pages = XhcAdv.dao.paginate(getPage(), getPageSize(), sqlPara);
		List<XhcAdv> items = pages.getList();
		setJsonItems(items);
		setRainbow(pages);
		setAttr("type", type);
		// setItems(JsonKit.toJson(advs));
		// System.out.println(JsonKit.toJson(items));
		render("/xhc/admin/adv/list.html");
	}

	@Override
	public void info() {
		Long id = getParaToLong("id");
		Integer type = getParaToInt("type", 1);
		XhcAdv adv = XhcAdv.dao.findById(id);
		if (adv == null) {
			adv = new XhcAdv();
			adv.setType(type);
		}
		// setAttr("adv", adv);
		setInfoItem(adv);
		render("/xhc/admin/adv/info.html");
	}

	public void qntoken() {
	}

	@Override
	public void submit() {
		Long id = getParaToLong("id");
		String title = getPara("title", "");
		String image = getPara("image", "");
		String url = getPara("url", "");
		if (StrKit.notBlank(url)) {
			boolean isUrl = false;
			if (url.contains("https://") || url.contains("http://")) {
				isUrl = true;
			}
			if (!isUrl) {
				url = "";
			}
		}
		Integer type = getParaToInt("type");
		XhcAdv adv = XhcAdv.dao.findById(id);
		if (adv == null) {
			adv = new XhcAdv();
			adv.setType(type);
			adv.save();
		}
		adv.setTitle(title);
		adv.setImage(image);
		adv.setUrl(url);
		boolean flag = adv.update();
		renderFlag(flag);

	}

	@Override
	public void delete() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure("id is null");
			return;
		}
		XhcAdv adv = XhcAdv.dao.findById(id);
		if (adv == null) {
			renderFailure("adv is null");
			return;
		}
		Boolean flag = adv.delete();
		if (flag) {
			renderSuccess();
		} else {
			renderMsg("删除失败");
		}
	}
}
